﻿using UnityEngine;
using System.Collections;

public class GameController : MonoBehaviour {

	//
	public static int score = 0;//得分
	public static bool showScore = false;//是否显示分数

	public GameObject startUI;//开始界面
	public GameObject gameUI;//游戏界面

	public GameObject container;//网格容器

	//public GameObject whieteBlock;//白色prefab
	//public GameObject normalBlock;//橙色prefab

	public GameObject[] prefabList;

	private ArrayList blocks;
	//进入游戏界面
	public void EnterGameUI(){
		startUI.SetActive (false);
		gameUI.SetActive (true);
		StartGame ();
		score = 0;
		showScore = true;
	}

	//退出游戏，返回开始界面
	public void BackToStartUI(){
		startUI.SetActive (true);
		gameUI.SetActive (false);
		showScore = false;
		//清理状态数据
		Clean ();

		//重置分数
		score = 0;
	}

	//开始游戏，布局初始网格
	private void StartGame(){

		blocks = new ArrayList ();
		for (int rowIndex = 0; rowIndex <4; rowIndex++) {
			AddBlock(rowIndex);
		}
	}

	//指定的行增加一个色块
	void AddBlock(int rowIndex){

		//随机数概率设定色块的类型
		int rnd = Random.Range (0, prefabList.Length);

		GameObject prefab = (GameObject)prefabList[rnd];
		GameObject o = GameObject.Instantiate(prefab) as GameObject;
		o.transform.parent = container.transform;
		Block block = o.GetComponent<Block>();
		block.blockType = rnd;
		block.canTouch = rnd>0;
		int columnIndex = Random.Range(0,4);
		block.SetPosition(rowIndex, columnIndex);

		//添加到blocks数组中
		blocks.Add (block);
	}

	public void Select(Block block){
		//播放声音
		audio.Play ();
		
		//计算得分
		score += block.blockType>0 ? block.blockType : -5;

		for (int i=0; i<blocks.Count; i++) {
			Block b = (Block)blocks[i];

			//色块下移
			b.MoveDown();

			//删除移除屏幕的色块
			if(b.rowIndex ==-1){
				blocks.RemoveAt(i);
				Destroy(b.gameObject);
				i--;
			}
		}
		//在最上面添加一个
		AddBlock (3);

	}

	//清理游戏状态数据
	void Clean(){
		if (blocks != null && blocks.Count>0) {
			for (int i=0; i<blocks.Count; i++) {
				Block b = (Block)blocks[i];
				blocks.RemoveAt(i);
				Destroy(b.gameObject);
				i--;
			}
		}
	}
}
